<script setup>
import {ref, onMounted} from "vue";
import tijianheader from "@/components/header.vue";
import {useRoute, useRouter} from "vue-router";
import axios from "axios";
import {ElMessage} from "element-plus";
import {format} from "date-fns";

const route = useRoute();
const router = useRouter();
const order = ref({});
const user = ref({});
const setmeal = ref({});
const showDetailsIndex = ref([]); // 修改为数组
const toggleDetails = (index) => {
    if (index >= 0 && index < showDetailsIndex.value.length) {
        showDetailsIndex.value[index] = !showDetailsIndex.value[index];
    }
};
const results = ref([]);
const result = ref([]);
const newresults = ref({
    title: "",
    content: "",
});
const fetchOrderDetails = async () => {
    try {
        const res = await axios.post("/api/order/orderdetail", {orderid: route.query.orderid});
        if (res.data.status === 200) {
            order.value = res.data.data;
            user.value = res.data.data.user;
            setmeal.value = res.data.data.setmeal;
        } else {
            console.error("获取数据失败: 响应数据格式不正确");
        }
    } catch (error) {
        console.error("请求失败:", error);
    }
};

const createcireportdetailed = async () => {
    try {
        const res = await axios.post("/api/report/createCireport", {
            orderid: route.query.orderid,
        });
    } catch (error) {
        console.error("请求失败:", error);
    }
};
const fetchResults = async () => {
    try {
        const res = await axios.post("/api/report/getReportList", {orderid: route.query.orderid});
        if (res.data?.data) {
            results.value = res.data.data;
        } else {
            console.error("获取数据失败: 响应数据格式不正确");
        }
    } catch (error) {
        console.error("请求失败:", error);
    }
};
const fetchoverresult = async () => {
    try {
        const res = await axios.post("/api/result/getListbyuser", {orderid: route.query.orderid});
        if (res.data?.data) {
            result.value = res.data.data;
        } else {
            console.error("获取数据失败: 响应数据格式不正确");
        }
    } catch (error) {
        console.error("请求失败:", error);
    }
};
onMounted(async () => {
    await Promise.all([fetchOrderDetails(), createcireportdetailed(), fetchoverresult(), fetchResults()]);
    showDetailsIndex.value = new Array(results.value.length).fill(false);
});
const isOutOfRange = (value, detail) => {
    if (value < detail.minrange || value > detail.maxrange) {
        return 1;
    } else {
        return 0;
    }
};
//添加数据到cidetailreport
const confirmResult = async (item) => {
    item.cidetailedreports.forEach((detail) => {
        detail.iserror = isOutOfRange(detail.value, detail);
    });

    await axios.put("/api/report/editValue", item.cidetailedreports).then((res) => {
        console.log(res);
    });
};

const editingRow = ref(null);
const editRow = (index) => {
    editingRow.value = index; // 设置当前编辑行
};

const saveUpdate = (index) => {
    // 可以在这里添加保存逻辑，例如：
    // axios.post('/api/update', results.value[index]);
    editingRow.value = null; // 保存后关闭编辑模式
};

const deleteRow = (index) => {
    results.value.splice(index, 1); // 删除该行
};
const addresult = async () => {
    result.value.push({
        ...newresults.value,
        orderid: route.query.orderid,
    }); // 添加新行
    console.log(result.value);
    newresults.value = {}; // 清空输入框内容
    await axios.post("/api/result/confirmResult", result.value).then((res) => {
        console.log(res);
    });
};
const handleReportExport = async () => {
    // 实际导出逻辑，可以是 API 调用等
    try {
        const res = await axios.put("/api/order/editOrder", {
            orderid: route.query.orderid,
            state: 3,
        });
        if (res.data.status === 200) {
            router.go(0);
        }
    } catch (error) {
        console.error(error);
    }
};
</script>

<template>
    <div class="exam-report-system">
        <tijianheader></tijianheader>
        <div class="main-content">
            <aside class="patient-info">
                <h2>预约客户信息</h2>
                <div class="info-item" v-if="order.orderid">
                    <label>预约编号</label>
                    <span>{{ order.orderid }}</span>
                </div>
                <div class="info-item" v-if="order.userid">
                    <label>手机号码</label>
                    <span>{{ order.userid }}</span>
                </div>
                <div class="info-item" v-if="order.user">
                    <label>真实姓名</label>
                    <span>{{ user.realname }}</span>
                </div>
                <div class="info-item" v-if="user.sex !== undefined">
                    <label>性别</label>
                    <span>{{ user.sex == 1 ? "男" : "女" }}</span>
                </div>
                <div class="info-item" v-if="setmeal.name">
                    <label>套餐类型</label>
                    <span>{{ setmeal.name }}</span>
                </div>
                <div class="info-item" v-if="order.orderdate">
                    <label>体检日期</label>
                    <span>{{ format(new Date(order.orderdate), "yyyy-MM-dd") }}</span>
                </div>
                <button class="query-button" @click="router.push('/reports')">查询体检用户</button>
            </aside>
            <main class="exam-results">
                <section class="exam-section" v-for="(item, index) in results" :key="index">
                    <div class="exam-header">
                        <h3>{{ item.ciname }}</h3>

                        <el-button @click="toggleDetails(index)" class="custom-button">
                            {{ showDetailsIndex[index] ? "隐藏详情" : "查看详情" }}
                        </el-button>
                    </div>

                    <div v-if="showDetailsIndex[index]" class="details">
                        <div class="result-grid">
                            <div
                                class="result-item"
                                v-for="(detail, detailIndex) in item.cidetailedreports"
                                :key="detailIndex"
                            >
                                <label>{{ detail.name }}:</label>
                                <input type="text" v-model="detail.value" />
                                <span class="unit">{{ detail.unit }}</span>
                                <span class="normal-range" v-if="detail.minrange && detail.maxrange">
                                    正常值范围:{{ detail.minrange }}{{ detail.unit }}-{{ detail.maxrange
                                    }}{{ detail.unit }}
                                </span>
                            </div>
                        </div>
                        <el-button
                            type="primary"
                            @click="confirmResult(item)"
                            class="custom-button"
                            v-show="order.state === 2"
                        >
                            {{ item.ciname }}保存
                        </el-button>
                    </div>
                </section>
                <!-- New layout starts here -->
                <div class="summary-section">
                    <div class="summary-header">
                        <h3>总检结论</h3>
                        <el-button
                            type="danger"
                            @click="handleReportExport"
                            class="export-button"
                            v-show="order.state === 2"
                        >
                            体检套餐总检结果报告归档
                        </el-button>
                    </div>
                    <table class="summary-table">
                        <thead>
                            <tr>
                                <th>编号</th>
                                <th>总检结论项标题</th>
                                <th>总检结论项内容</th>
                                <th v-show="order.state === 2">操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="(item, index) in result" :key="index">
                                <td>{{ index + 1 }}</td>
                                <td>
                                    <template v-if="editingRow === index">
                                        <input v-model="item.title" />
                                    </template>
                                    <template v-else>
                                        {{ item.title }}
                                    </template>
                                </td>
                                <td>
                                    <template v-if="editingRow === index">
                                        <input v-model="item.content" />
                                    </template>
                                    <template v-else>
                                        {{ item.content }}
                                    </template>
                                </td>
                                <td v-show="order.state === 2">
                                    <el-button v-if="editingRow === index" @click="saveUpdate(index)">保存</el-button>
                                    <el-button v-else @click="editRow(index)" type="primary">更新</el-button>
                                    <el-button type="danger" @click="deleteRow(index)">删除</el-button>
                                </td>
                            </tr>
                        </tbody>
                    </table>

                    <div class="summary-input" v-show="order.state === 2">
                        <label>总检结论项标题</label>
                        <input type="text" v-model="newresults.title" />
                        <label>总检结论项内容</label>
                        <textarea v-model="newresults.content"></textarea>
                    </div>

                    <div class="button-group" v-show="order.state === 2">
                        <el-button type="primary" @click="addresult">添加</el-button>
                        <el-button @click="newresults = {}">清空</el-button>
                    </div>
                </div>
            </main>
        </div>
    </div>
</template>

<style scoped>
.exam-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    /* margin-bottom: 10px; 增加标题与表格之间的间距 */
}

/* .exam-header h3 {
    font-size: 25px;
    font-weight: bold;
    margin-top: 0;
    margin-bottom: 0;
} */

.details {
    background-color: #f9fafb;
    border-radius: 5px;
    margin-bottom: 20px;
    max-height: 300px; /* 设置最大高度 */
    overflow-y: auto;  /* 超出内容显示滚动条 */
}


.custom-button {
    background-color: #3388ff; /* 按钮背景色 */
    color: white; /* 字体颜色 */
    border: none; /* 去除边框 */
    padding: 10px 20px; /* 内边距，控制按钮大小 */
    border-radius: 5px; /* 圆角 */
    cursor: pointer; /* 鼠标悬停效果 */
    font-size: 14px; /* 字体大小 */
    transition: background-color 0.3s; /* 背景颜色渐变效果 */
}

.custom-button:hover {
    background-color: #307cde; /* 鼠标悬停时的背景色 */
}

.exam-report-system {
    font-family: Arial, sans-serif;
    background-color: #b3c0d0;
    min-height: 100vh;
}

.main-content {
    display: flex;
    padding: 20px;
    background-color: #d3dce6;
}

.patient-info {
    background-color: #ffffff;
    padding: 20px;
    border-radius: 5px;
    width: 300px;
    margin-right: 20px;
}

.patient-info h2 {
    font-size: 16px;
    margin-top: 0;
    margin-bottom: 15px;
}

.info-item {
    margin-bottom: 10px;
}

.info-item label {
    font-weight: bold;
    display: block;
    margin-bottom: 5px;
}

.query-button {
    background-color: #2196f3;
    color: white;
    border: none;
    padding: 10px;
    border-radius: 5px;
    cursor: pointer;
    width: 100%;
    margin-top: 10px;
}

.exam-results {
    flex-grow: 1;
}

.exam-section {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    margin-bottom: 20px;
}

/* .exam-section h3 {
    font-size: 25px;
    font-weight: bold;
    margin-top: 0;
    margin-bottom: 15px;
} */

.result-grid {
    display: flex;
    flex-wrap: wrap;
     /* gap: 20px; 列之间的间距 */
}

.result-item {
    flex: 1 1 calc(50% - 20px); /* 每个项目占据50%宽度 */
    display: flex;
    align-items: center;
}
.result-item label {
    width: 180px;
    margin-right: 10px;
}

.result-item input {
    width: 80px;
    padding: 5px;
    border: 1px solid #ccc;
    border-radius: 3px;
}

.unit {
    margin-left: 5px;
    color: #666;
}

.normal-range {
    margin-left: 10px;
    color: #666;
    font-size: 12px;
}
.report-container {
    background-color: #f9fafb;
    padding: 20px;
    border-radius: 5px;
}

.summary-section {
    background-color: white;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.summary-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px; /* 增加标题与表格之间的间距 */
}
.summary-header h3 {
    font-size: 25px;
    font-weight: bold;
    margin-top: 0;
    margin-bottom: 0;
}
.export-button {
    margin-bottom: 20px;
    background-color: #f56c6c;
    color: white;
    width: 180px;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    padding: 10px;
}
/* 如果需要自定义更多样式，在这里添加 */

.summary-table thead {
    background-color: #f4f6f8;
}
.summary-table {
    width: 100%;
    border-collapse: collapse;
    margin-bottom: 20px;
}

.summary-table th,
.summary-table td {
    border: 1px solid #ddd;
    padding: 8px;
    text-align: left;
}

.summary-table th {
    background-color: #f4f6f8;
    font-weight: bold;
}

.summary-input {
    margin-bottom: 20px;
}

.summary-input label {
    display: block;
    margin-bottom: 5px;
}

.summary-input input,
.summary-input textarea {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
}

.button-group {
    display: flex;
    gap: 10px;
}
</style>
